import pymysql
from pyecharts.charts import Pie
from pyecharts import options as opts

db = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    passwd='111111',
    database='test',
    charset='utf8',
)
cursor = db.cursor()

sql = ("SELECT job_place, COUNT(job_id) as job_count "
       "FROM job "  # 替换为您的表名  
       "GROUP BY job_place")

total_count = 0  # 用于记录所有城市的岗位总数
city_data = []  # 用于存储城市名和岗位数量

try:
    cursor.execute(sql)
    res = cursor.fetchall()
    for row in res:
        job_place, job_count = row
        total_count += job_count
        city_data.append((job_place, job_count))

        # 计算每个城市的占比
    pie_data = [(city, count / total_count) for city, count in city_data]

    # 绘制饼图
    pie = Pie()
    pie.add(
        "",
        pie_data,
        radius=["0%", "75%"],
        label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"),
    )
    pie.set_global_opts(title_opts=opts.TitleOpts(title="各城市岗位数量占比"))
    pie.render("piera.html")

except :
    print("查询出错啦:")

cursor.close()
db.close()